package com.yy.controller;

import com.yy.po.Order;
import com.yy.po.OrderDetail;
import com.yy.po.OrderStatus;
import com.yy.util.Utils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbit;

    @RequestMapping("/order")
    public String order(Model model) throws Exception {
        List<OrderDetail> details = new ArrayList<>();
        OrderDetail od = new OrderDetail();
        od.setItemId(Utils.generateItemId());
        od.setItemName("苹果");
        od.setItemPrice(125);
        od.setNum(5);
        details.add(od);

        Order order = new Order();
        order.setUserId(Utils.generateUserId());
        order.setOrderId(Utils.generateOrderId());
        // 设置状态为待支付
        order.setStatus(OrderStatus.TO_BE_PAYED);
        order.setDetails(details);

        CorrelationData correlationData = new CorrelationData();
        rabbit.convertAndSend("x.order", "k.order", order, correlationData);

        // 同步等待；可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();

        // 判断发送的消息是否得到broke的确认
        boolean isAcked = confirm.isAck();

        if (!isAcked) return "failorder";

        // 发送延迟等待消息
        rabbit.convertAndSend("x.ttl", "k.ttl", order.getOrderId());

        model.addAttribute("orderId", order.getOrderId());

        return "order";
    }


    @RequestMapping("/failorder/{orderId}")
    public String failOrder(@PathVariable String orderId, Model model) {
        model.addAttribute("orderId", orderId);
        return "fail";
    }

}
